import 'dart:convert';
import 'dart:io';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _userNameController = new TextEditingController();
  TextEditingController _userPwdController = new TextEditingController();
  FocusNode _focusNodeUserPhone = new FocusNode();
  FocusNode _focusNodePassWord = new FocusNode();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  var _isShowClear = false; //是否显示输入框尾部的
  var _ShowPwd = false; //是否显示密码
  var _isShowClearPwd = false; //是否显示输入框尾部的
  bool isInstalledWechat = true;

  final TapGestureRecognizer private = TapGestureRecognizer();
  final TapGestureRecognizer userServer = TapGestureRecognizer();

  void authToQQ(BuildContext context) {
    SharesdkPlugin.getUserInfo(ShareSDKPlatforms.qq,
        (SSDKResponseState state, Map user, SSDKError error) {
      var qqInfo;
      if (Platform.isIOS) {
        qqInfo = user;
      } else {
        qqInfo = json.decode(user['dbInfo']);
      }
      qqPermit(qqInfo, context);
    });
  }

  void qqPermit(Map qqInfo, BuildContext context) {
    Provider.of<LoginViewModel>(context, listen: false).getQQPermit(qqInfo,
        onSuccess: (platform, openid, has_reg) {
      if (!has_reg) {
        Navigator.of(context).pushNamed(Routes.binding_phone,
            arguments: {'openid': openid, 'platform': platform});
      } else {
        Provider.of<LoginViewModel>(context, listen: false)
            .thirdPartLogin(platform, openid, onSuccess: () {
          Navigator.pop(context);
        });
      }
    });
  }

  void authToWechat(BuildContext context) {
    SharesdkPlugin.getUserInfo(ShareSDKPlatforms.wechatSession,
        (SSDKResponseState state, Map user, SSDKError error) {
      var wechatInfo;
      if (Platform.isIOS) {
        wechatInfo = user;
      } else {
        wechatInfo = json.decode(user['dbInfo']);
      }
      wechatPermit(wechatInfo, context);
    });
  }

  void wechatPermit(Map wechatInfo, BuildContext context) {
    Provider.of<LoginViewModel>(context, listen: false)
        .getWechatPermit(wechatInfo,
            onSuccess: (platform, openid, has_reg) {
              if (!has_reg) {
                Navigator.of(context).pushNamed(Routes.binding_phone,
                    arguments: {'openid': openid, 'platform': platform});
              } else {
                Provider.of<LoginViewModel>(context, listen: false)
                    .thirdPartLogin(platform, openid, onSuccess: () {
                  Navigator.pop(context);
                });
              }
            },
            onFail: (error) => Toast.show(error, context));
  }

  void authToSina(BuildContext context) {
    SharesdkPlugin.getUserInfo(ShareSDKPlatforms.sina,
        (SSDKResponseState state, Map user, SSDKError error) {
      var sinaInfo;
      if (Platform.isIOS) {
        sinaInfo = user;
      } else {
        sinaInfo = json.decode(user['dbInfo']);
      }
      sinaPermit(sinaInfo, context);
    });
  }

  void sinaPermit(Map sinaInfo, BuildContext context) {
    Provider.of<LoginViewModel>(context, listen: false).getSinaPermit(sinaInfo,
        onSuccess: (platform, openid, has_reg) {
      if (!has_reg) {
        Navigator.of(context).pushNamed(Routes.binding_phone,
            arguments: {'openid': openid, 'platform': platform});
      } else {
        Provider.of<LoginViewModel>(context, listen: false)
            .thirdPartLogin(platform, openid, onSuccess: () {
          Navigator.pop(context);
        });
      }
    });
  }

  void authToApple(BuildContext context) {
    SharesdkPlugin.cancelAuth(ShareSDKPlatforms.apple,(SSDKResponseState state, Map user, SSDKError error) {
      print('清除apple token 成功');
    }).then((value) {
      SharesdkPlugin.getUserInfo(ShareSDKPlatforms.apple,
          (SSDKResponseState state, Map user, SSDKError error) {
        if(error.code == 200000) {
          Toast.show('Apple登录仅支持ios13+', context);
        } else {
          applePermit(user, context);
        }
      });
    });
  }

  void applePermit(Map appleInfo, BuildContext context) {
    Provider.of<LoginViewModel>(context, listen: false).getApplePermit(appleInfo,
        onSuccess: (platform, openid, has_reg) {
          if (!has_reg) {
            Navigator.of(context).pushNamed(Routes.binding_phone,
                arguments: {'openid': openid, 'platform': platform});
          } else {
            Provider.of<LoginViewModel>(context, listen: false)
                .thirdPartLogin(platform, openid, onSuccess: () {
              Navigator.pop(context);
            });
          }
        });
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodeUserPhone.hasFocus) {
      print("用户名框获取焦点");

      // 取消密码框的焦点状态
      errormobile = null;
      _focusNodePassWord.unfocus();
    }
    if (_focusNodePassWord.hasFocus) {
      print("密码框获取焦点");
      // 取消用户名框焦点状态
      errorpass = null;
      (_formKey.currentState as FormState).reset();

      _focusNodeUserPhone.unfocus();
      errormobile = validateUserPhone(_userNameController.text);
    }
  }

  void hasWechatClient() {
    SharesdkPlugin.isClientInstalled(ShareSDKPlatforms.wechatSession)
        .then((value) {
      if (value['state'] == 'uninstalled') {
        setState(() {
          isInstalledWechat = false;
        });
      } else {
        setState(() {
          isInstalledWechat = true;
        });
      }
    });
  }

  @override
  void initState() {
    hasWechatClient();
    //监听用户名框的输入改变
    private.onTap = () {
      Navigator.of(context).pushNamed(Routes.policy);
    };
    userServer.onTap = () {
      Navigator.of(context).pushNamed(Routes.agreement);
    };
    _focusNodeUserPhone.addListener(_focusNodeListener);
    _focusNodePassWord.addListener(_focusNodeListener);
    _userNameController.addListener(() {
      print(_userNameController.text);
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userNameController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    _userPwdController.addListener(() {
      print(_userPwdController.text);
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPwdController.text.length > 0) {
        _isShowClearPwd = true;
      } else {
        _isShowClearPwd = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    _focusNodeUserPhone.removeListener(_focusNodeListener);
    _focusNodePassWord.removeListener(_focusNodeListener);
    _userNameController.dispose();
    _userPwdController.dispose();
    super.dispose();
  }

//

  /**
   * 验证用户名
   */
  String validateUserPhone(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (value.isEmpty) {
      return '手机号不能为空!';
    } else if (!exp.hasMatch(value)) {
      return '请输入正确手机号';
    }
    return null;
  }

  /**
   * 验证密码
   */
  String validatePassWord(value) {
    if (value.isEmpty) {
      return '密码不能为空';
    } else if (value.trim().length < 6 || value.trim().length > 18) {
      return '密码长度应该大于6位小于18位';
    }
  }

  var errormobile;
  var errorpass;

  Widget bodyWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 100.h),
          child: Text(
            "登录/注册",
            style: TextStyle(
              color: Color(0xFF000000),
              fontSize: 48.sp,
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 65.h),
          child: Form(
            key: _formKey,
            child: Column(
              children: <Widget>[
                new TextFormField(
                  onChanged: (v) {
                    return v.trim().length > 5 ? null : "密码不能少于6位";
                  },
                  focusNode: _focusNodeUserPhone,
                  style: TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
                  controller: _userNameController,
                  //设置键盘类型
                  keyboardType: TextInputType.number,
                  inputFormatters: [
                    WhitelistingTextInputFormatter.digitsOnly,
                    //限制只允许输入数字
                    LengthLimitingTextInputFormatter(11),
                    //限制输入长度不超过8位
                  ],

                  decoration: InputDecoration(
                    focusedErrorBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                      color: Color(0xFF0CABCB), //边框颜色为绿色
                      width: 2, //宽度为5
                    )),

                    errorText: errormobile,

                    errorStyle:
                        TextStyle(color: Color(0xFFFE0600), fontSize: 20.sp),
                    hintText: "请输入手机号",
                    hintStyle:
                        TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮
                    suffixIcon: (_isShowClear)
                        ? IconButton(
                            icon: Icon(
                              Icons.cancel,
                              size: 27.sp,
                            ),
                            onPressed: () {
                              // 清空输入框内容
                              _userNameController.clear();
                            },
                          )
                        : null,
                  ),

                  validator: validateUserPhone,
                ),
                new TextFormField(
                  focusNode: _focusNodePassWord,
                  style: TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
                  controller: _userPwdController,
                  obscureText: !_ShowPwd,
                  inputFormatters: [
                    LengthLimitingTextInputFormatter(18),
                    //限制输入长度不超过8位
                  ],
                  decoration: InputDecoration(
                    errorText: errorpass == "null" ? "" : errorpass,
                    focusedErrorBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                      color: Color(0xFF0CABCB), //边框颜色为绿色
                      width: 2, //宽度为5
                    )),
                    errorStyle:
                        TextStyle(color: Color(0xFFFE0600), fontSize: 20.sp),
                    suffixIcon: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        (_isShowClearPwd)
                            ? IconButton(
                                icon: Icon(
                                  Icons.cancel,
                                  size: 27.sp,
                                ),
                                onPressed: () {
                                  // 清空输入框内容
                                  _userPwdController.clear();
                                },
                              )
                            : Text(""),
                        IconButton(
                          iconSize: 30.sp,
                          icon: Icon((_ShowPwd)
                              ? Icons.visibility
                              : Icons.visibility_off),
                          onPressed: () {
                            setState(() {
                              _ShowPwd = !_ShowPwd;
                            });
                          },
                        ),
                      ],
                    ),
                    hintText: "密码",
                    hintStyle:
                        TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
                  ),
                  //密码验证
                  validator: validatePassWord,
                ),
                Padding(
                  padding: EdgeInsets.only(top: 20.h),
                  child: Row(
                    children: <Widget>[
                      Expanded(child: Constants.empty),
                      InkWell(
                        child: Text(
                          "忘记密码",
                          style: TextStyle(
                              fontSize: 20.sp, color: Color(0xFF82868E)),
                        ),
                        onTap: () {
                          Navigator.pop(context);
                          Navigator.of(context).pushNamed(Routes.forget);
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 120.h),
          width: 560.w,
          height: 80.h,
          color: Color(0xFF0CABCB),
          child: new FlatButton(
            child: new Text(
              '登录',
              style: TextStyle(fontSize: 30.sp, color: Color(0xFFF7F8F8)),
            ),
            onPressed: () {
              if ((_formKey.currentState).validate()) {
                context
                    .read<LoginViewModel>()
                    .login(_userNameController.text, _userPwdController.text,
                        onSuccess: () {
                  Navigator.of(context)
                      .popUntil(ModalRoute.withName(Routes.main_page));
                }, onFail: (error) {
                  decideError(error);
                  _focusNodeUserPhone.unfocus();
                  _focusNodePassWord.unfocus();
                });
              } else {
                _focusNodeUserPhone.unfocus();
                _focusNodePassWord.unfocus();
              }
            },
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 40.h),
          width: 560.w,
          height: 80.h,
          child: new FlatButton(
            child: new Text(
              '使用验证码登录',
              style: TextStyle(fontSize: 30.sp, color: Color(0xFF0CABCB)),
            ),
            onPressed: () {
              Navigator.of(context).popAndPushNamed(Routes.login_code_page);
            },
          ),
        ),
        Container(
          width: double.infinity,
          margin: EdgeInsets.only(top: 120.h),
          child: Center(
            child: Text(
              "— 使用第三方账号登录 —",
              style: TextStyle(
                color: Color(0xFF82868E),
                fontSize: 28.sp,
              ),
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 40.h),
          child:
            Platform.isIOS?
            Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              IconButton(
                icon: Image.asset(
                  "images/wechat.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToWechat(context);
                },
              ),
              IconButton(
                icon: Image.asset(
                  "images/share_qq.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToQQ(context);
                },
              ),
              IconButton(
                icon: Image.asset(
                  "images/share_weibo.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToSina(context);
                },
              ),
              IconButton(
                icon: Image.asset(
                  "images/share_apple.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToApple(context);
                },
              )
            ],
          ):
            Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            IconButton(
              icon: Image.asset(
                "images/wechat.png",
                height: 60.h,
                width: 69.w,
              ),
              onPressed: () {
                authToWechat(context);
              },
            ),
            IconButton(
              icon: Image.asset(
                "images/share_qq.png",
                height: 60.h,
                width: 69.w,
              ),
              onPressed: () {
                authToQQ(context);
              },
            ),
            IconButton(
              icon: Image.asset(
                "images/share_weibo.png",
                height: 60.h,
                width: 69.w,
              ),
              onPressed: () {
                authToSina(context);
              },
            ),
          ],
        )
        ),
        Container(
          margin: EdgeInsets.only(top: 120.h, bottom: 20.h),
          alignment: Alignment.bottomCenter,
          child: RichText(
              text: TextSpan(
                  text: '登录即同意LOXEN的',
                  style: TextStyle(color: Color(0xFFA0A0A0), fontSize: 25.sp),
                  children: <TextSpan>[
                TextSpan(
                    text: '《隐私政策》',
                    recognizer: private,
                    style:
                        TextStyle(color: Color(0xFF0CABCB), fontSize: 25.sp)),
                TextSpan(
                  text: '与',
                  style: TextStyle(color: Color(0xFFA0A0A0), fontSize: 25.sp),
                ),
                TextSpan(
                    text: '《用户协议》',
                    recognizer: userServer,
                    style: TextStyle(color: Color(0xFF0CABCB), fontSize: 25.sp))
              ])),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          "密码登录",
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 32.sp,
            color: Color(0xFF000000),
          ),
        ),
        actions: <Widget>[
          Container(
            child: FlatButton(
              padding: EdgeInsets.all(0.sp),
              child: Text(
                '注册',
                style: TextStyle(
                  color: Color(0xFF0CABCB),
                  fontSize: 32.sp,
                ),
              ),
              onPressed: () {
                Navigator.of(context).pushNamed(Routes.register);
              },
            ),
          ),
        ],
        backgroundColor: Colors.white,
        elevation: 0,
        leading: MySubassembly.getBackIcon(context, color: Colors.black),
      ),
      body: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onPanStart: (_) {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: SingleChildScrollView(
            child: Container(
                padding: EdgeInsets.only(left: 94.w, right: 94.w),
                child: bodyWidget()),
          )),
    );
  }

  void decideError(String T) {
    setState(() {
      if (T.length > 7) {
        errormobile = T;
        return;
      }
      if (T.length < 7) {
        errorpass = T;
        return;
      }
    });
  }
}
